var cheerio = require('cheerio')
var fs = require('fs')
var rp = require('request-promise')
var moment = require('moment')
var cheerio = require('cheerio')

var config = require('./config.js')
var util = require('./util/_default.js')
var xdl = require('./xdl.js')

var helper = util.helper
var dbHelper = util.dbHelper
var logHelper = util.logHelper
var yzmHelper = util.yzmHelper

//logHelper.init()

var args = process.argv.splice(2)

var tableId, page, allpage = 0

if (args.length == 2) {
    tableId = args[0]
    page = args[1]
    main()
} else {
    console.log('参数异常！')
}

function main() {
    console.log('批次[' + page + ']获取总页数信息')
    var opts = helper.deepCopy(config.reqOpts)
    opts.method = 'post'
    opts.url = 'http://appcfda.drugwebcn.com/datasearch/QueryList?tableId=' + tableId + '&searchF=Quick%20Search&searchK=&pageIndex=' + page + '&pageSize=15'
    rp(opts).then(function (body) {
        if (body == "") {
            main()
        }
        else {
            var d = JSON.parse(body)

            d.forEach(function (v, i, a) {
                if (allpage == 0) {
                    allpage = parseInt(v.COUNT / 15) + 1
                }
                var sql = 'insert into sfda' + tableId + 'Detail(cpId,cppage,cpStatus) values(@id, @page,0)'
                var param = {
                    id: v.ID,
                    page: page
                }
                dbHelper.qv(sql, param, function () {
                }, function (err) {
                    var msg = '数据保存出错。Error:' + err
                    console.log('批次[' + page + ']' + msg)
                })
            })
            if (page < allpage) {
                page = parseInt(page) + 1
                main()
            }
        }
    }).catch(function (err) {
        console.log('批次[' + page + ']' + '获取总页数信息出错，Error: ' + err)
        main()
    })
}

